package me.kuku.test;

import cn.u313.comm.interfacer.SendMsg;
import cn.u313.comm.interfacer.sendLister;
import cn.u313.comm.utils.MsgUtil;
import cn.u313.model.MsgInfo;
import lombok.SneakyThrows;
import lombok.val;
import love.forte.simbot.api.message.events.GroupMsg;
import love.forte.simbot.api.sender.MsgSender;
import me.kuku.pojo.QqLoginPojo;
import me.kuku.pojo.QqLoginQrcode;
import me.kuku.pojo.Result;
import me.kuku.pojo.UA;
import me.kuku.utils.MyUtils;
import me.kuku.utils.OkHttpUtils;
import me.kuku.utils.QqPasswordLoginUtils;
import me.kuku.utils.QqQrCodeLoginUtils;
import okhttp3.Response;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class QQlogin {
    public static Map<String,String> codeFilesMap = new HashMap<>();
    public static String code = "";
    public static String codeImg = "";

    public static  String realPath = "C:\\bot_105\\qqloginCode\\";
    private static final long appId = 716027609L;
    private static final int daId = 383;

    private static String catCodeImg = "[CAT:image,file=%s,flash=false]";
    private static final long ptAid = 100497308L;
    public static Result<String> login(MsgInfo msgInfo) throws IOException {
        //https://ssl.ptlogin2.qq.com/ptqrshow?appid=716027609&e=2&l
        // =M&s=3&d=72&v=4&t=0.4543303515614143&daid=383&pt_3rd_aid=100497308

            QqLoginQrcode qqLoginQrcode = null;
            try {
                qqLoginQrcode = QqQrCodeLoginUtils.getQrCode(appId, daId, ptAid);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(qqLoginQrcode);
            String base = "data:image/jpg;base64,"+qqLoginQrcode.getImageBase();
            if (!StringUtils.isEmpty(base)) {
                OutputStream out = null;
                try {
                    String base64 = base.split(",")[1];

                    byte[] bytes = Base64Utils.decode(base64.getBytes());
                    for (int i = 0; i < bytes.length; ++i) {
                        if (bytes[i] < 0) {
                            bytes[i] += 256;
                        }
                    }
                    String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
                    File file = new File(realPath);
                    if (!file.exists() || !file.isDirectory()) {
                        file.mkdirs();
                    }
                    codeImg = realPath + "/" + fileName;
                    out = new FileOutputStream(realPath + "" + fileName);
                    out.write(bytes);
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                try {
                    msgInfo.sendMsg(String.format(catCodeImg,codeImg));
                    return checkQrcode(qqLoginQrcode,msgInfo);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
    }
    public static Result<String> checkQrcode(QqLoginQrcode qqLoginQrcode,MsgInfo msgInfo) throws IOException {
        int i=0;
        while(i<100){
            i++;
            try {
                val result = QqQrCodeLoginUtils.checkQrCode(appId, daId, ptAid,
                        "https://graph.qq.com/oauth2.0/login_jump", qqLoginQrcode.getSig()
                );
                if(result.isFailure()){
                    System.out.println( result );
                }else{

                    System.out.println( result );

                    return getMusicKey(result,msgInfo);
                }
                Thread.sleep(3000);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
        msgInfo.sendMsg("超时！");
        return null;
    }

    static Result<String> getMusicKey(Result<QqLoginPojo> result,MsgInfo msgInfo) throws IOException {
        val urlResult = QqQrCodeLoginUtils.authorize(result.getData(), ptAid, "state",
                "https://y.qq.com/portal/wx_redirect.html?login_type=1&surl=https://y.qq.com/"
        );
        if (urlResult.isFailure()) return Result.failure(urlResult.getMessage());
        val url = urlResult.getData();
        val code = MyUtils.regex("code=", "&", url);
        System.out.println("code = "+code);
        val response = OkHttpUtils.post(
                "https://u.y.qq.com/cgi-bin/musicu.fcg",
                OkHttpUtils.addJson("{\"comm\":{\"g_tk\":5381,\"platform\":\"yqq\",\"ct\":24,\"cv\":0},\"req\":{\"module\":\"QQConnectLogin.LoginServer\",\"method\":\"QQLogin\",\"param\":{\"code\":\"" + code + "\"}}}")
        );
        response.close();
        val cookie = OkHttpUtils.getCookie(response);
        val key = OkHttpUtils.getCookie(cookie, "qqmusic_key");
        val qq = OkHttpUtils.getCookie(cookie, "uin");

        System.out.println("key="+key+" , qq="+qq);
        sendMusicKey(qq,key, msgInfo);
        return null;
    }

    private static void sendMusicKey(String qq, String key,MsgInfo msgInfo) throws IOException {
        if(key.length()<10){

            msgInfo.sendMsg("key is null!");
            return ;
        }
        Map<String, String> map = new HashMap<>();
        map.put("qq", qq);
        String ui = UUID.randomUUID().toString();
        map.put("ui", ui);
        map.put("key", key);
        map.put("userToken", "1054980699");
        Response response = OkHttpUtils.post("http://plugin.313u.cn/cgi_bin/rex/savefn1235444",
                map);
        String str = OkHttpUtils.getStr(response);

        msgInfo.sendMsg(str);
    }

    public static String pw() throws IOException {

        val result = QqPasswordLoginUtils.login(2036085374l,
                "anhao4455",appId,daId,"https://graph.qq.com/oauth2.0/login_jump");
        val urlResult = QqQrCodeLoginUtils.authorize(result.getData(), ptAid, "state",
                "https://y.qq.com/portal/wx_redirect.html?login_type=1&surl=https://y.qq.com/"
        );
        val url = urlResult.getData();
        val code = MyUtils.regex("code=", "&", url);
        System.out.println("code = "+code);
        val response = OkHttpUtils.post(
                "https://u.y.qq.com/cgi-bin/musicu.fcg",
                OkHttpUtils.addJson("{\"comm\":{\"g_tk\":5381,\"platform\":\"yqq\",\"ct\":24,\"cv\":0},\"req\":{\"module\":\"QQConnectLogin.LoginServer\",\"method\":\"QQLogin\",\"param\":{\"code\":\"" + code + "\"}}}")
        );
        response.close();
        val cookie = OkHttpUtils.getCookie(response);
        val key = OkHttpUtils.getCookie(cookie, "qqmusic_key");
        val qq = OkHttpUtils.getCookie(cookie, "uin");

        System.out.println("key="+key+" , qq="+qq);
        Map<String, String> map = new HashMap<>();
        map.put("qq", qq);
        String ui = UUID.randomUUID().toString();
        map.put("ui", ui);
        map.put("key", key);
        map.put("userToken", "1054980699");
        Response response0 = OkHttpUtils.post("http://plugin.313u.cn/cgi_bin/rex/savefn1235444",
                map);
        String str = OkHttpUtils.getStr(response0);
        return str;

    }
}
